<template>
  <view class="orders-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 自定义导航栏 -->
    <view class="top-nav">
      <view class="nav-center">
        <text class="nav-title">我的订单</text>
      </view>
    </view>

    <!-- 顶部筛选按钮 -->
    <view class="filters">
      <view 
        class="filter-btn" 
        :class="{ active: currentFilter === 'all' }"
        @click="setFilter('all')"
      >
        <text class="filter-icon">📋</text>
        <text class="filter-label">全部订单</text>
      </view>
      <view 
        class="filter-btn"
        @click="goToGroupBuyingPage"
      >
        <text class="filter-icon">👥</text>
        <text class="filter-label">拼单中</text>
      </view>
      <view 
        class="filter-btn" 
        :class="{ active: currentFilter === 'shipping' }"
        @click="setFilter('shipping')"
      >
        <text class="filter-icon">🚚</text>
        <text class="filter-label">待收货</text>
      </view>
      <view 
        class="filter-btn" 
        :class="{ active: currentFilter === 'refund' }"
        @click="setFilter('refund')"
      >
        <text class="filter-icon">💰</text>
        <text class="filter-label">退款中</text>
      </view>
    </view>

    <!-- 订单列表 -->
    <view class="list">
      <view 
        class="order-card"
        v-for="(order, idx) in filteredOrders" 
        :key="idx"
        @click="viewOrder(order)"
      >
        <view class="card-header">
          <text class="store">{{ order.storeName }}</text>
          <text 
            class="status" 
            :class="order.status"
          >
            {{ statusText(order) }}
          </text>
        </view>

        <view class="card-body">
          <image :src="order.image" mode="aspectFill" class="thumb" />
          <view class="info">
            <text class="name">{{ order.name }}</text>
            <text class="opts">{{ order.spice }} · {{ order.quantity }}份</text>
            <view class="price-row">
              <text class="total">总价 ¥{{ order.totalPrice }}</text>
            </view>
            <!-- 操作按钮：根据订单状态显示 -->
            <view class="actions" v-if="shouldShowActions(order)">
              <!-- 待支付：显示支付按钮和取消按钮 -->
              <template v-if="order.status === 'pending'">
                <button 
                  class="btn primary" 
                  @click.stop="payOrder(idx)"
                >
                  立即支付
                </button>
                <button 
                  class="btn outline" 
                  @click.stop="cancelOrder(idx)"
                >
                  取消订单
                </button>
              </template>
              
              <!-- 已支付/备货中：可以取消订单和申请退款 -->
              <template v-if="['paid', 'preparing'].includes(order.status)">
                <button 
                  class="btn outline" 
                  @click.stop="cancelOrder(idx)"
                >
                  取消订单
                </button>
                <button 
                  class="btn danger" 
                  @click.stop="refundOrder(idx)"
                >
                  申请退款
                </button>
              </template>
              
              <!-- 配送中：可以申请退款和确认收货 -->
              <template v-if="order.status === 'shipping'">
                <button 
                  class="btn danger" 
                  @click.stop="refundOrder(idx)"
                >
                  申请退款
                </button>
                <button 
                  class="btn primary" 
                  @click.stop="confirmDelivery(idx)"
                >
                  确认收货
                </button>
              </template>
              
              <!-- 已完成：显示评价按钮 -->
              <template v-if="order.status === 'delivered'">
                <button 
                  v-if="!order.isReviewed"
                  class="btn primary" 
                  @click.stop="goToReview(order)"
                >
                  去评价
                </button>
                <button 
                  v-else
                  class="btn outline" 
                  @click.stop="viewReview(order)"
                >
                  查看评价
                </button>
              </template>
            </view>
          </view>
        </view>
      </view>

      <view v-if="filteredOrders.length === 0" class="empty">暂无符合条件的订单</view>
    </view>
  </view>
  
  <!-- 底部导航栏 -->
  <view class="bottom-nav">
    <view class="nav-item" @click="goHome">
      <text class="nav-icon">🏠</text>
      <text class="nav-label">首页</text>
    </view>
    <view class="nav-item" @click="goGroupBuying">
      <text class="nav-icon">👥</text>
      <text class="nav-label">拼单</text>
    </view>
    <view class="nav-item active" @click="goOrders">
      <text class="nav-icon">📦</text>
      <text class="nav-label">订单</text>
    </view>
    <view class="nav-item" @click="goProfile">
      <text class="nav-icon">👤</text>
      <text class="nav-label">我的</text>
    </view>
  </view>
  
  <!-- AI助手悬浮球 -->
  <AIFloatingButton @open-chat="showAIChat = true" />
  
  <!-- AI聊天弹窗 -->
  <AIChatModal :visible="showAIChat" @update:visible="showAIChat = $event" />
  
  <!-- 自定义弹窗 -->
  <CustomModal ref="customModal" />
</template>

<script>
import orderService from '../../services/order.js'
import CustomModal from '../../components/CustomModal.vue'
import AIFloatingButton from '../../components/AIFloatingButton.vue'
import AIChatModal from '../../components/AIChatModal.vue'

export default {
  components: {
    CustomModal,
    AIFloatingButton,
    AIChatModal
  },
  data() {
    return {
      statusBarHeight: 0,
      currentFilter: 'all',
      loading: false,
      page: 1,
      pageSize: 10,
      hasMore: true,
      orders: [],
      // AI助手
      showAIChat: false
    }
  },
  computed: {
    filteredOrders() {
      if (this.currentFilter === 'all') {
        // 全部订单：显示所有订单
        return this.orders
      }
      
      if (this.currentFilter === 'shipping') {
        // 待收货：包括已支付、备货中、配送中的订单
        return this.orders.filter(o => ['paid', 'preparing', 'shipping'].includes(o.status))
      }
      
      if (this.currentFilter === 'refund') {
        // 退款中：包括退款中、已退款、已取消的订单
        return this.orders.filter(o => ['refund', 'refunded', 'cancelled'].includes(o.status))
      }
      
      return this.orders
    }
  },
  onLoad(options) {
    this.getStatusBarHeight()
    
    // 接收筛选参数
    if (options.filter) {
      const f = options.filter
      if (['all','shipping','refund'].includes(f)) {
        this.currentFilter = f
      }
    }
    
    // 加载订单列表
    this.loadOrders()
  },
  
  onShow() {
    this.getStatusBarHeight()
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
      document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px')
    },
    
    // 跳转到拼单活动页面
    goToGroupBuyingPage() {
      uni.navigateTo({
        url: '/pages/group-buying/group-buying'
      })
    },
    
    // 加载订单列表
    async loadOrders(refresh = false) {
      if (this.loading) return
      
      if (refresh) {
        this.page = 1
        this.orders = []
        this.hasMore = true
      }
      
      if (!this.hasMore) return
      
      this.loading = true
      
      try {
        const params = {
          page: this.page,
          perPage: this.pageSize
        }
        
        console.log('加载订单列表 - 参数:', params)
        
        const response = await orderService.getOrderList(params)
        console.log('订单列表响应:', response)
        
        if (response && response.data) {
          const ordersData = response.data.orders || response.data
          
          if (Array.isArray(ordersData)) {
            // 格式化订单数据
            const formattedOrders = ordersData.map(order => 
              orderService.formatOrderForList(order)
            )
            
            if (refresh) {
              this.orders = formattedOrders
            } else {
              this.orders = [...this.orders, ...formattedOrders]
            }
            
            // 检查是否还有更多数据
            if (ordersData.length < this.pageSize) {
              this.hasMore = false
            } else {
              this.page++
            }
            
            console.log('订单列表加载成功，共', this.orders.length, '条')
          }
        }
        
      } catch (error) {
        console.error('加载订单列表失败:', error)
        
        let errorMsg = '加载订单失败'
        if (error.message && error.message.includes('401')) {
          errorMsg = '请先登录'
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/login/login'
            })
          }, 1500)
        }
        
        uni.showToast({
          title: errorMsg,
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    setFilter(f) { 
      this.currentFilter = f
      this.loadOrders(true)
    },
    statusText(order) {
      return order.statusText || orderService.getStatusText(order.status)
    },
    
    // 判断是否显示操作按钮
    shouldShowActions(order) {
      // 已取消、已退款的订单不显示操作按钮
      // 已完成的订单显示评价按钮
      return !['cancelled', 'refunded'].includes(order.status)
    },
    
    // 跳转评价页面
    goToReview(order) {
      uni.navigateTo({
        url: `/pages/order-review/order-review?orderId=${order.id}`
      })
    },
    
    // 查看评价
    viewReview(order) {
      uni.navigateTo({
        url: `/pages/my-reviews/my-reviews?orderId=${order.id}`
      })
    },
    
    // 支付订单
    async payOrder(index) {
      const order = this.filteredOrders[index]
      
      this.$refs.customModal.show({
        type: 'confirm',
        title: '确认支付',
        content: `订单金额：¥${order.totalPrice}\n\n是否确认支付？`,
        confirmText: '确认支付',
        cancelText: '取消',
        onConfirm: async () => {
          try {
            // 显示支付中
            uni.showLoading({
              title: '支付处理中...',
              mask: true
            })
            
            // 模拟支付延迟
            await new Promise(resolve => setTimeout(resolve, 1500))
            
            // 调用支付接口
            await orderService.payOrder(order.id, 'mock_payment')
            
            uni.hideLoading()
            
            uni.showToast({
              title: '支付成功',
              icon: 'success',
              duration: 2000
            })
            
            // 刷新订单列表
            setTimeout(() => {
              this.loadOrders(true)
            }, 500)
            
          } catch (error) {
            uni.hideLoading()
            console.error('支付失败:', error)
            
            let errorMsg = '支付失败'
            if (error.message) {
              if (error.message.includes('404')) {
                errorMsg = '订单不存在'
              } else if (error.message.includes('400')) {
                errorMsg = '订单状态异常'
              }
            }
            
            uni.showToast({
              title: errorMsg,
              icon: 'error'
            })
          }
        }
      })
    },
    
    // 确认收货
    async confirmDelivery(index) {
      const order = this.filteredOrders[index]
      
      // 状态检查：只有配送中的订单才能确认收货
      if (order.status !== 'shipping') {
        uni.showToast({
          title: '当前订单状态无法确认收货',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      this.$refs.customModal.show({
        type: 'success',
        title: '确认收货',
        content: '确认已收到商品吗？\n\n确认后订单将完成，无法撤销。',
        confirmText: '确认收货',
        cancelText: '再等等',
        onConfirm: async () => {
          try {
            // 调用后端确认收货接口
            await orderService.confirmReceipt(order.id)
            
            // 确认成功提示
            uni.showToast({
              title: '确认收货成功',
              icon: 'success',
              duration: 2000
            })
            
            // 延迟后询问是否评价
            setTimeout(() => {
              this.$refs.customModal.show({
                type: 'info',
                title: '给个好评吧',
                content: '您的评价对我们很重要，是否现在去评价？',
                confirmText: '去评价',
                cancelText: '下次再说',
                onConfirm: () => {
                  // 跳转到评价页面
                  uni.navigateTo({
                    url: `/pages/order-review/order-review?orderId=${order.id}`
                  })
                },
                onCancel: () => {
                  // 刷新订单列表
                  this.loadOrders(true)
                }
              })
            }, 800)
            
          } catch (error) {
            console.error('确认收货失败:', error)
            
            let errorMsg = '确认收货失败'
            if (error.message) {
              if (error.message.includes('404')) {
                errorMsg = '订单不存在'
              } else if (error.message.includes('400')) {
                errorMsg = '订单状态异常，无法确认收货'
              } else if (error.message.includes('401')) {
                errorMsg = '请先登录'
              }
            }
            
            uni.showToast({
              title: errorMsg,
              icon: 'error',
              duration: 2500
            })
          }
        }
      })
    },
    viewOrder(order) {
      uni.navigateTo({
        url: `/pages/order-detail/order-detail?id=${order.id}`
      })
    },
    async cancelOrder(index) {
      const order = this.filteredOrders[index]
      
      this.$refs.customModal.show({
        type: 'warning',
        title: '取消订单',
        content: '确定要取消该订单吗？',
        confirmText: '确定取消',
        cancelText: '再想想',
        onConfirm: async () => {
          try {
            await orderService.cancelOrder(order.id, '用户取消')
            
            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            })
            
            // 重新加载订单列表
            this.loadOrders(true)
            
          } catch (error) {
            console.error('取消订单失败:', error)
            uni.showToast({
              title: '取消失败',
              icon: 'error'
            })
          }
        }
      })
    },
    
    async refundOrder(index) {
      const order = this.filteredOrders[index]
      
      this.$refs.customModal.show({
        type: 'danger',
        title: '申请退款',
        content: '确认要申请退款吗？',
        confirmText: '确认退款',
        cancelText: '取消',
        showInput: true,
        inputPlaceholder: '请输入退款原因（选填）',
        inputMaxLength: 100,
        onConfirm: async (inputValue) => {
          try {
            const reason = inputValue || '用户申请退款'
            await orderService.refundOrder(order.id, reason)
            
            uni.showToast({
              title: '退款申请已提交',
              icon: 'success'
            })
            
            // 重新加载订单列表
            this.loadOrders(true)
            
          } catch (error) {
            console.error('申请退款失败:', error)
            uni.showToast({
              title: '申请失败',
              icon: 'error'
            })
          }
        }
      })
    },
    
    // 取消拼单
    cancelGroupBuy(index) {
      const order = this.filteredOrders[index]
      this.$refs.customModal.show({
        type: 'warning',
        title: '取消拼单',
        content: '确定要取消该拼单吗？',
        confirmText: '确定取消',
        cancelText: '再想想',
        onConfirm: () => {
          // 在原始orders中找到并更新状态
          const id = this.orders.indexOf(order)
          if (id !== -1) this.$set(this.orders, id, { ...order, status: 'cancelled' })
          uni.showToast({ title: '已取消拼单', icon: 'none' })
        }
      })
    },
    
    // 底部按钮
    // 底部导航按钮
    goHome() { uni.redirectTo({ url: '/pages/home/home' }) },
    goGroupBuying() { uni.redirectTo({ url: '/pages/group-buying/group-buying' }) },
    goOrders() { /* 已经在订单页，不执行跳转 */ return },
    goProfile() { uni.redirectTo({ url: '/pages/profile/profile' }) }
  }
}
</script>

<style lang="scss" scoped>
.orders-container { min-height: 100vh; background: #fff; }
.status-bar { position: fixed; top: 0; left: 0; right: 0; background: #fff; z-index: 999; }

.top-nav { position: fixed; top: var(--status-bar-height); left: 0; right: 0; height: 88rpx; display: flex; align-items: center; justify-content: center; background: #fff; border-bottom: 1rpx solid #eee; z-index: 998; }
.nav-title { font-size: 32rpx; font-weight: 700; color: #333; }

.filters { 
  position: fixed;
  top: calc(var(--status-bar-height) + 88rpx);
  left: 0;
  right: 0;
  display: flex; 
  justify-content: space-around; 
  gap: 10rpx; 
  padding: 16rpx 20rpx; 
  background: #fff; 
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  z-index: 997;
}

.filter-btn { 
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4rpx;
  padding: 12rpx 8rpx;
  border-radius: 12rpx;
  border: 2rpx solid #ffe0b2;
  background: linear-gradient(135deg, #fff7ec 0%, #fffaf0 100%);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
  }
  
  .filter-icon {
    font-size: 28rpx;
    transition: transform 0.3s ease;
  }
  
  .filter-label {
    font-size: 20rpx;
    color: #ff8a00;
    font-weight: 600;
    text-align: center;
    transition: color 0.3s ease;
  }
  
  &.active {
    background: linear-gradient(135deg, #ff8a00 0%, #ffa726 100%);
    border-color: transparent;
    box-shadow: 0 4rpx 12rpx rgba(255, 138, 0, 0.3);
    
    .filter-icon {
      transform: scale(1.08);
    }
    
    .filter-label {
      color: #fff;
    }
  }
  
  &:active .filter-icon {
    transform: scale(1.02);
  }
}

.list { 
  margin-top: calc(var(--status-bar-height) + 88rpx + 160rpx); 
  padding: 20rpx 24rpx 140rpx;
  background: #fff;
  min-height: calc(100vh - var(--status-bar-height) - 88rpx - 160rpx);
}
.order-card { background: #fff; border-radius: 20rpx; padding: 24rpx; margin-bottom: 24rpx; border: 2rpx solid #ffe0b2; }
.card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16rpx; }
.store { font-size: 28rpx; color: #333; font-weight: 600; }
.status { font-size: 24rpx; color: #999; }
.status.shipping { color: #ff8a00; }
.status.refund { color: #f44336; }
.status.done { color: #4caf50; }
.status.cancelled { color: #9e9e9e; }
.status.groupbuying { color: #2196f3; }

.card-body { display: flex; gap: 16rpx; }
.thumb { width: 120rpx; height: 120rpx; border-radius: 12rpx; background: #f0f0f0; }
.info { flex: 1; display: flex; flex-direction: column; justify-content: space-between; }
.name { font-size: 28rpx; color: #333; font-weight: 600; }
.opts { font-size: 24rpx; color: #666; margin: 6rpx 0; }
.total { font-size: 28rpx; color: #ff4757; font-weight: 700; }

.empty { text-align: center; color: #999; padding: 60rpx 0; }

.actions { display: flex; gap: 16rpx; margin-top: 12rpx; }
.btn { height: 64rpx; padding: 0 20rpx; border-radius: 32rpx; font-size: 24rpx; }
.btn.outline { background: #fff; color: #333; border: 2rpx solid #ddd; }
.btn.danger { background: #ffebee; color: #e53935; border: 2rpx solid #ffcdd2; }

/* 底部导航栏 */
.bottom-nav {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 120rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  z-index: 999;
  
  .nav-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8rpx;
    padding: 12rpx 0;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    
    &:active {
      transform: scale(0.95);
    }
    
    .nav-icon {
      font-size: 44rpx;
      transition: all 0.3s ease;
      filter: grayscale(100%);
      opacity: 0.6;
    }
    
    .nav-label {
      font-size: 22rpx;
      color: #999;
      font-weight: 500;
      transition: all 0.3s ease;
    }
    
    /* 选中状态 */
    &.active {
      .nav-icon {
        filter: grayscale(0%);
        opacity: 1;
        transform: scale(1.1);
      }
      
      .nav-label {
        color: #667eea;
        font-weight: 600;
      }
      
      /* 选中指示器 */
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 6rpx;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 3rpx;
      }
    }
  }
}
</style>
